/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package carpool.services;

import carpool.persistence.Utilizadores;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author sdinis
 */
public class UserServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        //response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession();
        PrintWriter out = response.getWriter();

        String op = request.getParameter("operation");

        if ("check_username".equals(op)){
            UserBean ub = new UserBean();
            String u = request.getParameter("rusername");
            if (ub.getUser(u) != null) {
                out.write("false");
            } else
            {
                out.write("true");
            }
       }

       //operation LOGIN
       if ("auth".equals(op)){

           // authenticate in userBean

           //if OK, add userbean to session
           Utilizadores user = new Utilizadores();
           user.setNome("John Peter Parents");
           HashSet emails = new HashSet();
           emails.add("jpp@dei.uc.pt");
           user.setEmailses(emails);
           user.setId(123456778);
           session.setAttribute("user", user);
           //if not ok, return error
       }

       //operation REGISTER
        if ("register".equals(op)) {
            try {
                DateFormat df = new SimpleDateFormat ("yyyy/MM/dd"); //"1981/02/05"

                UserBean ub = new UserBean();
                /*
                operation: "register",
                number: $('#reg_numero').val(),
                name: $('firstname').val()+" "+$('lastname').val(),
                gender: $('input[name=gender]:checked').val(),
                birth: $("#birth").datepicker("getDate"),
                address: $('#address').val(),
                email: $('#email').val(),
                username: $('#rusername').val(),
                password: $('#rpassword').val()
                 */

                HashSet emails = new HashSet();
                emails.add(request.getParameter("email"));
                HashSet addresses = new HashSet();
                addresses.add(request.getParameter("address"));

                Utilizadores user = new Utilizadores(
                        request.getParameter("name"),
                        request.getParameter("gender"),
                        df.parse(request.getParameter("birth")),
                        request.getParameter("number"),
                        request.getParameter("username"),
                        request.getParameter("password"),        
                        new byte[10]);
                user.setEmailses(emails);
                user.setMoradases(addresses);
                
                response.setContentType("text/xml");
                response.setHeader("Cache-Control", "no-cache");
                
                if (ub.createAndStoreUser(user)) {
                    out.write("<xml><res>User created!</res></xml>");
                } else {
                    out.write("<xml><error>Unable to create user.</error></xml>");
                }
            } catch (Exception ex) {
                Logger.getLogger(UserServlet.class.getName()).log(Level.SEVERE, null, ex);
                out.write("<xml><error>An error occured registering your account.\nPlease try again later.</error></xml>");
            }
        }

    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
